package com.ljkj.blockpay.widget;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;

import java.lang.ref.WeakReference;

/**
 * Created by yp on 2022/3/1
 */
public class DialogViewHelper {
    private SparseArray<WeakReference<View>> mViews;

    private View mContentView;

    public DialogViewHelper(Context context, @LayoutRes int layoutResId){
        this();
        mContentView = LayoutInflater.from(context).inflate(layoutResId,null,false);
    }

    public DialogViewHelper() {
        mViews = new SparseArray<>();
    }

    /**
     * 设置view
     * @param contentView
     */

    public void setContentView(View contentView){
        this.mContentView = contentView;
    }


    public <T extends View> T getView(@IdRes int viewId ){
        WeakReference<View> viewReference = mViews.get(viewId);
        View view = null;
        if (viewReference != null){
            view = viewReference.get();
        }
        if (view == null){
            view = mContentView.findViewById(viewId);
            if (view != null){
                mViews.put(viewId,new WeakReference<>(view));
            }
        }

        return (T)view;
    }

    /**
     * 设置文本
     * @param viewId
     * @param text
     */
    public void setText(@IdRes int viewId,CharSequence text){
        TextView textView = getView(viewId);
        if (textView != null){
            textView.setText(text);
        }
    }

    /**
     * 设置view点击事件
     * @param viewId
     * @param listener
     */
    public void setOnclickListener(@IdRes int viewId, final View.OnClickListener listener){
        View view  = getView(viewId);
        if (view != null){
            view.setOnClickListener(listener);
        }
    }

    /**
     * 隐藏显示View
     * @param viewId
     * @param visibility
     */
    public void setGone(@IdRes int viewId, int visibility){
        View view = getView(viewId);
        if (view != null){
            view.setVisibility(visibility);
        }
    }

    /**
     *
     * @return 获取当前dialog view
     */
    public View getContentView(){
        return mContentView;
    }
}
